package nrpc.client.slst;

import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import nrpc.client.serst.ConfiguredServiceStrategy;
import nrpc.client.serst.ServiceNode;
import nrpc.client.serst.ServiceStrategy;
import nrpc.client.skst.SingleSocketStrategy;
import nrpc.client.skst.SocketStrategy;

public class SingleSelectStrategy implements SelectStrategy {
	
//	private final static long TIMEOUT = 10000;
	
	private ServiceStrategy serviceStrategy;
	
	private Set<ServiceNode> nodes = new HashSet<>();
	
	public SingleSelectStrategy(InetSocketAddress address) {
		this(new ConfiguredServiceStrategy(address));
	}
	
	public SingleSelectStrategy(ServiceStrategy serviceStrategy) {
		this.serviceStrategy = serviceStrategy;
		this.serviceStrategy.subscribe(
				(addedNode)->{
					synchronized(this){
						nodes.add(addedNode);
						this.notifyAll();
					}
				}, 	
				(deletedNode)->{
					synchronized(this){
						nodes.remove(deletedNode);
					}
				});
//		this.socketWrapper = socketStrategy.getSocketWrappers().get(0);
	}

	@Override
	public Iterator<ServiceNode> getNode(Method method, List<Object> args) {
		return nodes.iterator();
	}

	@Override
	public synchronized void deleteNode(ServiceNode node) {
		nodes.remove(node);
	}
	
	@Override
	public void close() {
		this.serviceStrategy.close();
	}
	
//	@Override
//	public void deactivate(SocketChannel channel) {
//		this.socketWrapper.backSocketChannel(channel);
//	}

//	@Override
//	public void close() {
//		super.close();
//		this.serviceStrategy.close();
//	}

//	@Override
//	protected synchronized Iterator<? extends ServiceNode> getServiceQueue() {
//		while(nodes.size() == 0)
//			try {
//				this.wait(TIMEOUT);
//			} catch (InterruptedException e) {}
//		return nodes.iterator();
//	}

	
	
	
}
